package com.frontop.system.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frontop.system.modules.sys.mapper.SysOrganizationMapper;
import com.frontop.system.modules.sys.model.SysOrganization;
import com.frontop.system.modules.sys.service.SysOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YangJia
 * @since 2022-01-10
 */
@Service
public class SysOrganizationServiceImpl extends ServiceImpl<SysOrganizationMapper, SysOrganization> implements SysOrganizationService {
    @Autowired
    SysOrganizationMapper sysOrganizationMapper;
    /**
     * 根据ID查询所有子级组织
     * @param id
     * @return
     */
    @Override
    public List<SysOrganization> getOrgTree(Integer id) {
        List<SysOrganization> list = sysOrganizationMapper.findAllChildNode(id);
        SysOrganization sysOrganization = getById(id);
        list.add(sysOrganization);
        return recursionForList(sysOrganization.getPId(),list);
    }

    @Override
    public Integer deleteOrganization(Integer id) {
        List<Integer> nodeId = sysOrganizationMapper.findAllChildNodeId(id);
        for(Integer node : nodeId){
            sysOrganizationMapper.updateStatus(node);
        }
        sysOrganizationMapper.updateStatus(id);
        return nodeId.size()+1;
    }

    @Override
    public List<Integer> findAllChildNodeId(Integer id) {
        return sysOrganizationMapper.findAllChildNodeId(id);
    }


    private List<SysOrganization> recursionForList(int parentId, List<SysOrganization> orgList) {
        List<SysOrganization> list = new ArrayList<>();
        Optional.ofNullable(orgList).orElse(new ArrayList<>())
                .stream()
                //找出本次循环中所有子元素
                .filter(org -> org.getPId().equals(parentId))
                .forEach(org -> {
                    //将这些子元素 赋值到子列表的元素中 继续递归寻找下级
                    org.setChildren(recursionForList(org.getId(), orgList));
                    list.add(org);
                });
        return list;
    }

}
